package com.ztomorrow.ying_cun_plus.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ztomorrow.ying_cun_plus.dao.mapper.BookInfoMapper;
import com.ztomorrow.ying_cun_plus.dao.po.BookInfo;
import com.ztomorrow.ying_cun_plus.dto.EsBookDto;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

import static com.ztomorrow.ying_cun_plus.constant.author.SystemConstant.INDEX_BOOK;

@Component
@RequiredArgsConstructor
public class ESInit {

    private final BookInfoMapper bookInfoMapper;
    private final RestHighLevelClient client;

    public void Init() throws IOException {
        BulkRequest request = new BulkRequest(INDEX_BOOK);
        List<BookInfo> bookInfos = bookInfoMapper.selectList(new LambdaQueryWrapper<BookInfo>()
                .gt(BookInfo::getWordCount, 0));
        for (BookInfo bookInfo : bookInfos) {
            IndexRequest indexRequest = new IndexRequest().id(bookInfo.getId().toString());
            indexRequest.source(
                    JSONUtil.toJsonStr(BeanUtil.copyProperties(bookInfo, EsBookDto.class)),
                    XContentType.JSON);
            request.add(indexRequest);
        }

        client.bulk(request, RequestOptions.DEFAULT);

    }
}
